<template>
  <view :class="showItem? 'my_index_wraper':'my_index_wraper1' ">
    <view class="phone_wraper">
      <button v-if="!phoneNumber" id="phone" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="phone_main">
        <view class="user_info">
          <img class="l_tu" :src="avatarUrl" />
          <view class="phone_title">请授权登录</view>
        </view>
      </button>
      <view class="phone_main" v-else>
        <view class="user_info">
          <img class="l_tu" src="../../static/fuel/user.png" />
          <view class="val_pho">
            <view class="enterpriseName">{{maskedPhoneNumber(userInfo.mobilePhone) }}</view>
            <view class="lab">
              <view class="phone_name">NO.{{ userInfo.memberCode }}</view>
              <view class="grade">
                <img v-if="userInfo.gradeCode === '1'" src="../../static/fuel/userlevel_pu.png" alt="用户级别" />
                <img v-if="userInfo.gradeCode === '2'" src="~static/fuel/userlevel_yin.png" alt="用户级别"/>
                <img v-if="userInfo.gradeCode === '3'" src="~static/fuel/userlevel_jin.png" alt="用户级别"/>
                <img v-if="userInfo.gradeCode === '4'" src="~static/fuel/userlevel_zhuan.png" alt="用户级别" />
                <img v-if="userInfo.gradeCode === '5'" src="~static/fuel/userlevel_black.png" alt="用户级别"/>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="main_wraper_nav" v-if="!phoneNumber">
        <button class="btn" id="phone" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
          <view class="num">{{ userInfo.integral || 0 }}</view>
          <view class="text">积分</view>
        </button>
        <button class="btn" id="phone" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
          <view class="num">{{ userInfo.balance || 0 }}</view>
          <view class="text">加油卡余额</view>
        </button>
        <button class="btn" id="phone" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
          <view class="num">{{ userInfo.couponCount || 0 }}</view>
          <view class="text">优惠劵</view>
        </button>
      </view>
      <view class="main_wraper_nav" v-else>
        <navigator class="item" @click="goOfficialPoint('/point/charge')">
          <view class="num">{{ userInfo.balance || 0 }}</view>
          <view class="text">加油卡</view>
        </navigator>
        <navigator class="item" @click="goOfficialNow('/coupon/index')">
          <view class="num">{{ userInfo.couponCount || 0 }}</view>
          <view class="text">优惠劵</view>
        </navigator>
        <navigator class="item" @click="goOfficialPoint('/point/index')">
          <view class="num">{{ userInfo.integral || 0 }}</view>
          <view class="text">积分</view>
        </navigator>
      </view>
      <view class="vip">
        <view class="vip_icon">
          <view>
            <img src="../../static/fuel/vip.png" alt="" />
            <text>{{ userInfo.gradeName || "普卡" }}会员</text>
          </view>
          <view>欢迎加入会员</view>
        </view>
        <view class="vip_equity">
          <text>会员权益</text>
        </view>
      </view>
    </view>
    <view class="my_index">
      <footer :class="showItem ?'bottom':'otherBottom' ">
        <view v-if="showItem">
          <view class="app_model" v-if="!phoneNumber">
              <uni-grid :column="4" :show-border="false">
                <uni-grid-item v-for="(item,index) in modelList" :index="index" :key="item.code">
                  <button class="btn" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
                    <view class="item">
                      <image style="width: 100rpx;height:100rpx;" :src="item.img" mode="scaleToFill"/>
                      <view class="text">{{item.text}}</view>
                    </view>
                  </button>
                </uni-grid-item>
              </uni-grid>
          </view>
          <view class="app_model" v-else>
            <uni-grid :column="4" :show-border="false" @change="goOfficialNow">
              <uni-grid-item v-for="(item,index) in modelList" :index="index" :key="item.code">
                <view class="item">
                  <image style="width: 100rpx;height:100rpx;" :src="item.img" mode="scaleToFill"/>
                  <view class="text">{{item.text}}</view>
                </view>
              </uni-grid-item>
            </uni-grid>
          </view>
        </view>
        <view v-else>
          <view v-if="!phoneNumber">
            <view class="btn_app_models">
              <button class="btn_phone" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-for="(item,index) in modelList" :key="item.code">
                <view class="btn_model">
                  <image style="width: 52rpx;height:52rpx;" :src="item.img" mode="scaleToFill"/>
                  <view class="item_text">{{item.text}}</view>
                </view>
                <view class="icon"><image src="../../static/fuel/left.png" mode="scaleToFill"/></view>
              </button>
            </view>
          </view>
          <view v-else>
            <view class="app_models" v-for="(item,index) in modelList" :key="item.code" @click="goOfficialNow(item.toPath)">
                <view class="item_model">
                  <image style="width: 52rpx;height:52rpx;" :src="item.img" mode="scaleToFill"/>
                  <view class="item_text">{{item.text}}</view>
                </view>
                <view class="icon"><image src="../../static/fuel/left.png" mode="scaleToFill"/></view>
            </view>
          </view>
        </view>
      </footer>
    </view>
  </view>
</template>

<script>
import { mapMutations } from "vuex";
import WXBizDataCrypt from "./WXBizDataCrypt.js";
import settings from "@/settings.js";
export default {
  data() {
    return {
      avatarUrl:"https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
      showGoApplet: true,
      infoData: {},
      scanShow: false,
      initShow: false,
      userInfo: {},
      // stationId: 226, // 康裕石化 生产的id
      // stationId: 239,  //  康裕石化 测试的id
      // stationId: 1419, // 南坑石化
      stationId: settings.stationId,
      issueId: "",
      session_key: "",
      userList: {},
      modelList:[
      {text:'我的订单',code:0,toPath:'/record/consume',img: require('../../static/fuel/order.png')},
      {text:'油站导航',code:1,toPath:'/fuel/fuel',img:require('../../static/fuel/map.png')},
      {text:'个人资料',code:2,toPath:'/setting/info',img:require('../../static/fuel/user.png')},
      {text:'今日油价',code:3,toPath:'/nowPrice/index',img:require('../../static/fuel/oilPrice.png')},
      {text:'快捷加油',code:4,toPath:'/fuel/fuel',img:require('../../static/fuel/quick_refuel.png')},
      ],//应用列表
      showItem:true,
    };
  },
  computed: {
    // 展示的油站信息
    showPhone() {
      const phone = this.phoneNumber + "";
      return phone.replace(phone.substring(3, 7), "****");
    },
  },
  onLoad(option) {
    console.log("settings:", settings);
    // this.updateEnterpriseId("137"); // 康裕石化 生产的id
    // this.updateEnterpriseId("194"); // 康裕石化 测试的id
    // this.updateEnterpriseId("666");
    this.updateEnterpriseId(settings.enterpriseId);
    if (option.q && option.q != "undefined") {
      // 获取到二维码原始链接内容
      const qrUrl = decodeURIComponent(option.q);
      //此处就是我们要获取的参数 json，通过方法解析
      let jsonUrl = this.GetwxUrlParam(qrUrl);
      //比如我要得到id的值，直接取值即可
      let enterpriseId = jsonUrl.enterpriseId;
      this.stationId = jsonUrl.stationId;
      console.log(jsonUrl, "巡逻点ID：" + enterpriseId);
      this.enterpriseId = enterpriseId;
      this.updateEnterpriseId(enterpriseId);
      this.initShow = true;
    } else {
      this.initShow = true;
    }
  },
  onShow() {
    const this_ = this;
    if (this.phoneNumber) {
      this.getUserInfo();
    } else {
      this.getOpenId();
    }
    if (!this.userInfo) {
      wx.getUserInfo({
        success: function (res) {
          this_.gender = res.userInfo.gender;
        },
      });
    }
  },
  watch: {
    phoneNumber(newval, oldval) {
      if (this.phoneNumber) {
        console.log("监控到手机号的变化：", newval);
        console.log(this);
        this.getUserInfo();
      }
    },
    enterpriseId(newval, oldval) {
      // 康裕石化能源： 生产id是 137  测试id是194
      // 南坑石化： 666
      // if (this.enterpriseId !== "666") {
      //   this.getOpenId();
      // }
      if (this.enterpriseId !== settings.enterpriseId) {
        this.getOpenId();
      }
    },
  },
  methods: {
    ...mapMutations({
      updateOpenId: "updateOpenId",
      updatePhoneNumber: "updatePhoneNumber",
      updateEnterpriseId: "updateEnterpriseId",
      updateuserInfoFull: "updateuserInfoFull",
    }),
    goOfficialPoint(url) {
      // if (!this.phoneNumber) {
      //   uni.showToast({
      //     title: "请授权登录",
      //     icon: "error",
      //   });
      //   return;
      // }
      uni.navigateTo({
        url: `/subPackB${url}`,
      });
    },
     maskedPhoneNumber(phoneNumber) {
      const visibleDigits = 3; // 前三位可见
      const maskedDigits = phoneNumber&&phoneNumber.length - visibleDigits - 4; // 中间的数字用*代替
      const maskedPart = '*'.repeat(maskedDigits);
      const lastFourDigits = phoneNumber&&phoneNumber.slice(-4); // 后四位可见
      return `${phoneNumber&&phoneNumber.slice(0, visibleDigits)}${maskedPart}${lastFourDigits}`;
    },
    GetwxUrlParam(url) {
      let theRequest = {};
      if (url.indexOf("#") != -1) {
        const str = url.split("#")[1];
        const strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
      } else if (url.indexOf("?") != -1) {
        const str = url.split("?")[1];
        const strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
      }
      return theRequest;
    },
    goOfficialNow(val) {
      if (!this.phoneNumber) {
        uni.showToast({
          title: "请授权登录",
          icon: "error",
        });
        return;
      }
      if(this.showItem){ 
        let selectedModel =this.modelList[val.detail.index]
        uni.navigateTo({
          url: `/subPack${selectedModel.toPath}`,
        });
      }else{ 
      uni.navigateTo({
        url: `/subPack${val}`,
      });
      }
      
    },

    async getUserInfo() {
      try {
        if (this.phoneNumber) {
          const infoData = await this.$Request({
            url: "/selectMemberInfo",
            method: "GET",
            data: {
              enterpriseId: this.enterpriseId,
              mobilePhone: this.phoneNumber,
            },
          });
          if (infoData.retCode !== 0) {
            throw new Error(infoData.message);
          }
          this.userInfo = infoData.data;
          this.updateuserInfoFull(infoData.data);
        }
      } catch (error) {}
    },
    scanCode() {
      // 允许从相机和相册扫码
      uni.scanCode({
        success: function (res) {
          console.log("条码类型：" + res.scanType);
          console.log("条码内容：" + res.result);
        },
      });
    },
    goOfficial() {
      this.$refs.child.goOfficial();
    },

    async getOpenId() {
      const this_ = this;
      uni.login({
        provider: "weixin",
        success: async (res) => {
          this_.code = res.code;
          // const gzhAuthenRes = await this.$Request({
          //   url: "/getPaySessionKeyAndOpenID",
          //   method: "GET",
          //   data: {
          //     code: res.code,
          //     enterpriseId: this.enterpriseId,
          //   }
          // });
          // if (gzhAuthenRes.retCode === 0) {
          //   const openId = gzhAuthenRes.data.openId;
          //   this_.session_key=gzhAuthenRes.data.sessionKey
          //   this_.updateOpenId(openId)
          // }
        },
      });
    },

    // 获取手机号
    async getPhoneNumber(info) {
      console.log("点击获取手机号", info);
      uni.showLoading({
        title: "获取中...",
        mask: true,
      });
      console.log(info);
      if (info.detail.errMsg === "getPhoneNumber:ok") {
        // let pc = new WXBizDataCrypt('wx3d56fc8b214444d2', this.session_key);
        // let pc = new WXBizDataCrypt('wxf24a5561a44f6d55', this.session_key); //
        // let data = pc.decryptData(info.detail.encryptedData , info.detail.iv);
        const encryptedData = info.detail.encryptedData;
        const iv = info.detail.iv;
        const infoData = await this.$Request({
          url: "/loginGetPhone",
          method: "GET",
          data: {
            code: this.code,
            stationId: this.stationId,
            encryptedData,
            iv,
            version: 2,
            blogNickName: "微信用户",
            sexFlag: this.gender || 0,
            blogProfilePhoto: this.avatarUrl,
          },
        });
        const openId = infoData.data.openId;
        this.updateOpenId(openId);
        const phone = infoData.data.phoneNumber;
        this.phoneNumber = infoData.data.phoneNumber;
        this.updatePhoneNumber(phone);
        uni.hideLoading();
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "请授权登录~",
          icon: "error",
        });
        this.getOpenId();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.my_index_wraper {
  background-color: #FFFFFF;
  width: 100vw;
  box-sizing: border-box;
  min-height: 100vh;
  .phone_wraper {
    padding: 23rpx 25rpx 0rpx;
    box-sizing: border-box;
    width: 100%;
    background: url('../../static/fuel/bgc.png') no-repeat 0 0;
    background-size: 100% 100%;

    .top_title {
      color: #000;
      font-size: 34rpx;
      margin: 50rpx 0 40rpx;
      height: 40rpx;
      letter-spacing: 4rpx;
      font-weight: 500;
    }

    .main_wraper_nav {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 48rpx 21rpx 30rpx 33rpx;
      button {
        margin: 0 !important;
        border: none;
        padding: 0 !important;
        .num {
          color: #000;
          font-size: 36rpx;
          line-height: 48rpx;
        }
        .text {
          color: #5b5b5b;
          font-size: 26rpx;
          text-align: center;
          margin-top: 21rpx;
          letter-spacing: 4rpx;
        }
      }
      .item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .text {
          color: #5b5b5b;
          font-size: 25rpx;
          text-align: center;
          width: 150rpx;
          margin-top: 10rpx;
          letter-spacing: 4rpx;
        }
      }
    }
    .vip {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: url("../../static/fuel/pk.png") no-repeat 0 0;
      border-radius: 30rpx 30rpx 0 0;
      padding: 28rpx 21rpx 26rpx 26rpx;
      .vip_icon {
        display: flex;
        flex-direction: column;
        view:first-child {
          display: flex;
          color: #fff;
          text {
            font-size: 26rpx;
          }
          img {
            width: 47rpx;
            height: 43rpx;
            object-fit: cover;
            padding-right: 22rpx;
          }
        }
        view:last-child {
          padding-top: 18rpx;
          font-size: 18rpx;
          color: #fff;
        }
      }
      .vip_equity {
        font-size: 18rpx;
        color: #000;
        line-height: 45rpx;
        height: 45rpx;
        border-radius: 20rpx;
        width: 113rpx;
        text-align: center;
        background: linear-gradient(to right, #f4e9bf, #f1d99f);
      }
    }
    .phone_main {
      display: flex;
      width: 100%;
      height: 100rpx;
      align-items: center;
      padding: 0 !important;
      // padding: 20rpx 30rpx;
      box-sizing: border-box;
      //margin-top: 100rpx;
      color: #000;
      border: none;

      .user_info {
        display: flex;
        align-items: center;
        .l_tu {
          overflow: hidden;
          border-radius: 50%;
          height: 100rpx;
          width: 100rpx;
          margin: 0 14rpx 0rpx 5rpx;
        }

        .val_pho {
          display: flex;
          flex-direction: column;
          justify-content: center;
          color: #000;
          .enterpriseName {
            font-size: 34rpx;
            color: #000;
          }
          .phone_name {
            font-size: 24rpx;
            letter-spacing: 4rpx;
            color: #999999;
            padding-top: 29rpx;
          }
          .lab {
            display: flex;
            align-items: center;
            .grade {
              padding-top: 23rpx;
              width: 70rpx;
              height: 30rpx;
              margin-left: 16rpx;
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }
        }

        .phone_title {
          // margin-top: -10rpx;
          font-size: 34rpx;
          letter-spacing: 4rpx;
          margin-left: 14rpx;
        }
      }
    }
  }
}
.my_index_wraper1{ 
  background-color: #F3F4F5;
  width: 100vw;
  box-sizing: border-box;
  min-height: 100vh;
  .phone_wraper {
    //padding: 50rpx 35rpx 0rpx;
    padding: 23rpx 25rpx 0rpx;
    box-sizing: border-box;
    width: 100%;
    background: url('../../static/fuel/bgc.png') no-repeat 0 0;
    background-size: 100% 100%;

    .top_title {
      color: #000;
      font-size: 34rpx;
      margin: 50rpx 0 40rpx;
      height: 40rpx;
      letter-spacing: 4rpx;
      font-weight: 500;
    }

    .main_wraper_nav {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 48rpx 21rpx 30rpx 33rpx;
      button {
        margin: 0 !important;
        border: none;
        padding: 0 !important;
        .num {
          color: #000;
          font-size: 36rpx;
          line-height: 48rpx;
        }
        .text {
          color: #5b5b5b;
          font-size: 26rpx;
          text-align: center;
          margin-top: 21rpx;
          letter-spacing: 4rpx;
        }
      }
      .item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .text {
          color: #5b5b5b;
          font-size: 25rpx;
          text-align: center;
          width: 150rpx;
          margin-top: 10rpx;
          letter-spacing: 4rpx;
        }
      }
    }
    .vip {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: url("../../static/fuel/pk.png") no-repeat 0 0;
      border-radius: 30rpx 30rpx 0 0;
      padding: 28rpx 21rpx 26rpx 26rpx;
      .vip_icon {
        display: flex;
        flex-direction: column;
        view:first-child {
          display: flex;
          color: #fff;
          text {
            font-size: 26rpx;
          }
          img {
            width: 47rpx;
            height: 43rpx;
            object-fit: cover;
            padding-right: 22rpx;
          }
        }
        view:last-child {
          padding-top: 18rpx;
          font-size: 18rpx;
          color: #fff;
        }
      }
      .vip_equity {
        font-size: 18rpx;
        color: #000;
        line-height: 45rpx;
        height: 45rpx;
        border-radius: 20rpx;
        width: 113rpx;
        text-align: center;
        background: linear-gradient(to right, #f4e9bf, #f1d99f);
      }
    }
    .phone_main {
      display: flex;
      width: 100%;
      height: 100rpx;
      align-items: center;
      padding: 0 !important;
      // padding: 20rpx 30rpx;
      box-sizing: border-box;
      //margin-top: 100rpx;
      color: #000;
      border: none;

      .user_info {
        display: flex;
        align-items: center;
        .l_tu {
          overflow: hidden;
          border-radius: 50%;
          height: 100rpx;
          width: 100rpx;
          margin: 0 14rpx 0rpx 5rpx;
        }

        .val_pho {
          display: flex;
          flex-direction: column;
          justify-content: center;
          color: #000;
          .enterpriseName {
            font-size: 34rpx;
            color: #000;
          }
          .phone_name {
            font-size: 24rpx;
            letter-spacing: 4rpx;
            color: #999999;
            padding-top: 29rpx;
          }
          .lab {
            display: flex;
            align-items: center;
            .grade {
              padding-top: 23rpx;
              width: 70rpx;
              height: 30rpx;
              margin-left: 16rpx;
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }
        }

        .phone_title {
          // margin-top: -10rpx;
          font-size: 34rpx;
          letter-spacing: 4rpx;
          margin-left: 14rpx;
        }
      }
    }
  }
}
.bacggroud_wraper {
  width: 100%;
  box-sizing: border-box;

  .bacggroud_wraper_val {
    width: 100%;
    box-sizing: border-box;
    height: 180rpx;
  }
}

.my_index {
  .bottom {
    width: 100%;
    box-sizing: border-box;
    padding: 9rpx 35rpx;
    box-sizing: border-box;
    background-color: #fff;
    .app_model{ 
      /deep/ .uni-grid-item { 
        height: unset !important;
      }
      .btn{
        border: unset;
      }
      .item{ 
        padding-top: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        .text{ 
          margin-top: 15rpx;
          color: #333;
          font-size: 24rpx;
        }
      }
    }
  }
  .otherBottom{ 
    width: 100%;
    box-sizing: border-box;
    padding: 7rpx 25rpx 0 19rpx;
    box-sizing: border-box;
    height: 100%;
    overflow: auto;
    background-color: #F3F4F5;
    .app_models{ 
      margin-top: 15rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 25rpx 22rpx 24rpx 18rpx;
      background-color: #fff;
      border-radius: 15rpx;
      .item_model{ 
        margin-top: 13rpx;
        display: flex;
        align-items: center;
        .item_text{ 
          padding-left: 30rpx;
          font-size: 28rpx;
          color: #333;
        }
      }
      .icon{ 
        width: 14rpx;
        height: 24rpx;
        image{ 
          height:100%;
          width: 100%;
        }
      }
    }
    .btn_app_models{ 
      .btn_phone{
        border: unset !important;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #fff;
        padding-left: 18rpx;
        padding-right: 22rpx;
        margin-top: 13rpx;
        .btn_model{ 
          display: flex;
          align-items: center;
          .item_text{ 
            padding-left: 30rpx;
            font-size: 28rpx;
            color: #333;
          }
        }
        .icon{ 
          image{ 
            width: 14rpx;
            height: 24rpx;
          }
        }
      }
    }
  }
}
</style>
